public class test3 {
    public static void main(String[] args) {
        //输出1~20000的所有素数并记录开始时间
        long startTime = System.nanoTime();

        int count = 0;
        for (int number = 2; number <= 20000; number++) {
            if (!isPrime(number)) {
                System.out.print(number + " ");
                count++;
                if (count % 5 == 0) {
                    System.out.println();
                }
            }
        }
        // 记录结束时间
        long endTime = System.nanoTime();

        // 计算执行时间，并将其转换为毫秒
        long duration = (endTime - startTime) / 1_000_000;
        // 输出执行时间



        //埃拉托斯特尼筛法
        long startTime2 = System.nanoTime();
        boolean[] prime2 = new boolean[20001];
        for (int i = 2; i * i <= 20000; i++) {
            if (prime2[i]) continue;
            for (int j = i * i; j <= 20000; j += i) {
                prime2[j] = true;
            }
        }

        int count2 = 0;
        for (int number = 2; number <= 20000; number++) {
            if (!prime2[number]) {
                System.out.print(number + " ");
                count++;
                if (count2 % 5 == 0) {
                    System.out.println();
                }
            }
        }
        long endTime2 = System.nanoTime();
        long duration2 = (endTime2 - startTime2) / 1_000_000;
        //对比两种方法时间
        System.out.println("程序1执行时间（毫秒）: " + duration);
        System.out.println("程序2执行时间（毫秒）：" + duration2);

    }


    public static boolean isPrime(int number) {
        if (number <= 1) return false;
        for (int i = 2; i * i <= number; i++) {
            if (number % i == 0) {
                return false;
            }
        }
        return true;
    }
}
